<template>
  <div class="login-container">
    <div class="title-container">
      <h3 class="title">智慧工地信息系统平台</h3>
    </div>
    <div class="content">
      <!-- <div class="left">
        <img src="../../assets/images/login-img.png" alt="">
      </div> -->
      <div class="right">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
          <!-- <div class="title-img">
            <img src="../../assets/images/login-title.png" alt="">
          </div> -->
          <el-form-item prop="userName">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="userName"
              v-model="loginForm.userName"
              placeholder="请输入用户名"
              name="userName"
              type="text"
              tabindex="1"
              auto-complete="off"
            />
          </el-form-item>

          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              auto-complete="off"
              @keyup.enter.native="handleLogin"
            />
          <!-- <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span> -->
          </el-form-item>

          <el-form-item prop="captcha_code">
            <span class="svg-container">
              <svg-icon icon-class="yzm" />
            </span>
            <el-input
              v-model="loginForm.captcha_code"
              placeholder="验证码"
              autocomplete="off"
              autocapitalize="off"
              type="text"
              spellcheck="false"
              minlength="4"
              tabindex="3"
              width="200px"
              style="width: 122px;height: 36px;color:#606266;"
              @keyup.enter.native="handleLogin"
            />
            <div class="captcha_code">
              <img
                ref="code"
                style="width: 80px;height: 38px;"
                base
                :src="'data:image/png;base64,' +loginForm.captcha"
                @click="changeCode"
              >
            </div>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <!-- <span class="f_pwd">忘记密码</span> -->
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>

        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { switchProject } from '@/api/project'
import axios from 'axios'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('用户名不能为空!'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length <= 20 && value.length >= 8) {
        callback()
      } else {
        callback(new Error('密码不能为空!'))
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value.length > 0) {
        callback()
      } else {
        callback(new Error('请输入正确的验证码'))
      }
    }
    return {
      loginForm: {
        userName: '',
        password: '',
        captcha: '',
        captcha_code: '',
        captchaId: '',
        rememberMe: false
      },
      loginRules: {
        userName: [
          { required: true, trigger: 'blur', validator: validateUsername }
          // { min: 2, max: 7, message: '长度在 2 到 7 个字符' },
          // { pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文' }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword },
          { min: 8, max: 20, message: '密码由8-20个大小写字母、数字、特殊字符组成' },
          { pattern: /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])).{8,20}$/, message: '密码由8-20个大小写字母、数字、特殊字符组成' }
        ],
        captcha_code: [
          { required: true, trigger: 'blur', validator: validateCode }
        ]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  computed: {
    ...mapGetters([
      'projectsId',
      'projects'
    ])
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    this.changeCode()
  },
  methods: {
    changeCode() {
      axios.get(
        process.env.VUE_APP_BASE_API + '/user/picCaptcha')
        .then(response => {
          if (response.data.code === 200) {
            this.loginForm.captcha = response.data.data.base64Captcha
            this.loginForm.captchaId = response.data.data.id
          } else {
            this.loginForm.captcha = ''
            this.loginForm.captchaId = ''
          }
        }).catch(function(error) {
          console.log(error)
        })
    },

    /** 密码查看
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },*/

    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(async(res) => {
            if (res.code !== 200) {
              Message({
                message: res.data.msg || 'Error',
                type: 'error',
                showClose: true,
                center: true,
                duration: 2 * 1000
              })
            } else {
              if (!res.data.isFirst) {
                if (res.data.projects.length === 0) {
                // 新建工程引导页
                  this.$router.push('/newNetwork')
                } else {
                  // 添加切换工程请求，默认第一个请求返回成功后跳转到首页
                  const id = res.data.projects[0].id
                  const res2 = await switchProject(id)
                  if (res2.code === 200) {
                    // this.$store.commit('user/SET_PROJECTSID', id)
                    const roles = res2.data.permissions || ['']
                    window.localStorage.setItem('roles', JSON.stringify(roles))
                    this.$store.dispatch('permission/generateRoutes', roles)
                    this.$router.push({ path: 'dashboard' })
                  } else {
                    Message({
                      message: res.data.msg || 'Error',
                      type: 'error',
                      showClose: true,
                      duration: 2 * 1000
                    })
                  }
                }
              } else {
                // window.localStorage.clear()
                this.$router.push({ path: 'revisePwd', query: {
                  id: res.data.userRsp.id
                }})
              }
              this.loading = false
            }
          }).catch(() => {
            this.changeCode()
            this.loading = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */

// $bg:#2d3a4b;
$bg:#fff;
$light_gray:#fff;
$cursor: black;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
    // border-radius: 5px;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      // background: transparent;
      // border: 0px;
      // background:rgba(255,255,255,1);
      // border-radius:4px;
      // border:1px solid rgba(217,217,217,1);
      // -webkit-appearance: none;
      // border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: black;
      height: 40px;
      border: 0px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        // -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    height: 46px;
    background:rgba(255,255,255,1);
    border-radius:4px;
    border:1px solid rgba(217,217,217,1);
    // border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 5px;
    color: #D3D3D3;
  }
  .el-checkbox__inner{
    width:12px;
    height:12px;
    border-radius:2px;
    // border:1px solid rgba(19,156,217,1);
    background-color: transparent;
  }
  .el-checkbox__input.is-focus .el-checkbox__inner{
    border-color:  #666;
  }
  .el-checkbox__input.is-checked+.el-checkbox__label{
    color: #F7B500;
  }
  .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner{
    border-color: #F7B500;
    background: #F7B500;
  }
}
</style>

<style lang="scss" scoped>
$bg:#072041;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  // background: url('../../assets/images/login-bg.png') no-repeat;
  // background-size:100% 100%;
  // -moz-background-size:100% 100%;
  overflow-y: auto;
  overflow-x: hidden;
  // display: flex;
  .el-checkbox{
    margin-left: 16px;
    font-weight:400;
    color:rgba(255,255,255,0.5);
    margin-bottom: 10px;
    margin-top: 15px;
  }

  .login-form {
    // position: relative;
    width: 35%;
    // max-width: 100%;
    // border-radius: 4px;
    padding: 35px 35px 0 35px;
    // background: url('../../assets/images/login-input.png') no-repeat;
    // background-size:100% 100%;
  //  -moz-background-size:100% 100%;
    margin: 0 auto;
    // margin-top: 88px;
    // margin-right: 20%;
    .el-button--primary{
      background:rgba(247,181,0,1);
      border-color: rgba(247,181,0,1);
      border-radius:4px;
      // background:#F7B500;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    // flex: 1;
    .title {
          height: 36px;
          font-size: 29px;
          color: #fff;
          line-height: 41px;
          text-align: center;
          margin: 174px 0 0 0;
          // margin: 41px 0 41px 60px;
    }
  }
  .content{
    display: flex;
    .left{
      flex: 1;
      margin: 70px 0 0 32px;
      img{
         width: 710px;
      }
    }
    .right{
      flex: 1;
      .title-img{
        width: 292px;
        margin: 0 auto;
        padding: 0px 0 20px 0;
      }
      .captcha_code{
        float: right;
        // position: absolute;
        margin: 6px 10px 0px 0;
      }
    }

  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
.f_pwd{
  margin-top: 15px;
  float: right;
  cursor: pointer;
  color: rgba(255,255,255,.5);
  &:hover{
    color: rgba(247,181,0,1);
  }
}
</style>
